package coderead.agent.jvmtool;
/**
 * @fankang
 */


import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;


public class Bootstrap {

    static int port = 7766;
    private final ToolService toolService;

    public Bootstrap() throws RemoteException, NotBoundException, MalformedURLException {
        // 加载远程服务
        toolService = (ToolService) Naming.lookup("rmi://localhost:" + port + "/ToolService");
    }

    public static void main(String[] args) throws Exception {
        // 获取jvm进程列表
        System.out.println("启动服务");
        List<VirtualMachineDescriptor> list = VirtualMachine.list();
        for (int i = 0; i < list.size(); i++) {
            System.out.println(String.format("[%s] %s", i, list.get(i).displayName()));
            //System.out.println(list.get(i).id());
        }

        // 选择jvm进程
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        String line = read.readLine();
        int i = Integer.parseInt(line);
        // 附着agent
        VirtualMachine virtualMachine = VirtualMachine.attach(list.get(i));
        File file = new File(SystemPath.class.getProtectionDomain().getCodeSource().getLocation().getPath());

        virtualMachine.loadAgent(file.getParent()+"\\javaagent-1.0-SNAPSHOT.jar", String.valueOf(port));

        virtualMachine.detach();
        System.out.println("加载成功");

        Bootstrap bootstrap = new Bootstrap();
        while (true) {
            line = read.readLine().trim();
            if (line.equals("exit")) {
                break;
            }
            try {
                bootstrap.runCommand(line);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void runCommand(String cmdAndParams) throws Exception {
        String[] s = cmdAndParams.split(" ");
        String cmd = s[0];
        String result;
        if (cmd.equals("sc")) {
            result = toolService.findClassName(s[1]);
        } else if (cmd.equals("jad")) {
            result = toolService.jadClass(s[1]);
        } else if(cmd.equals("method")) {
            result = toolService.getClassAllMethods(s[1] , "");
        } else if(cmd.equals("modif")) {
            Scanner in = new Scanner(System.in);
            System.out.println("输入前置逻辑");
            String[] befor = in.next().split(" ");

            System.out.println("输入后置逻辑");
            String[] after = in.next().split(" ");

            if(s.length==3) {
                result = toolService.modfiymethod(s[1] , s[2] , befor , after);
            } else {
                result = "arg was not enable to execut function , this mean you need input [command] [targetclass] [targetmethod]" ;
            }


        } else if(cmd.equals("recover")) {
            if(s.length==3) {
                result = toolService.recovermethod(s[1] , s[2]) ;
            } else {
                result = "arg was not enable to execut function , this mean you need input [command] [targetclass] [targetmethod]" ;
            }

        }
          else if(cmd.equals("size")) {
            result = Long.toString(toolService.getClasssize(s[1]));
        } else if(cmd.equals("getinstance")) {
              result = toolService.getCurrliveObject(s[1]);
        } else if(cmd.equals("attribut")){
           result = toolService.getClassAttributes(s[1]);
           // Set<String> strings = classAttributes.keySet();

        }
        else {
            System.err.println("不支持的命令:" + cmdAndParams);
            return;
        }
        System.out.println(result);
        //new HelloWorld().hello();
    }

}
